/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * diagAAutoCorredor.java
 *
 * Created on Oct 11, 2011, 10:39:28 PM
 */
package carreras.gui;

import carreras.Configuracion;
import carreras.Utilidades;
import carreras.entidades.Auto;
import carreras.entidades.CatCorredorAuto;
import carreras.entidades.Corredor;
import carreras.entidades.CorredorAuto;
import carreras.negocio.NegCorredorAuto;
import data.DBConnector;
import java.awt.event.KeyEvent;
import java.sql.SQLException;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author fanky
 */
public class diagAAutoCorredor extends javax.swing.JDialog {
    private static final String TITLE = "Auto-Corredor";
    public static boolean CANCELADO = true;
    private CatCorredorAuto corredores_usados;
    private CorredorAuto corredor_auto;
    private CatCorredorAuto corredor_autoV;
    //este arreglo sirve para 'saber' que se le muestra al usuario en la tabla y cuando seleccione tomar el mismo objeto
    private CatCorredorAuto corredor_autoV_filtrado;
    public diagAAutoCorredor(java.awt.Frame parent,CatCorredorAuto corredores_usados) {
        this(parent,true,corredores_usados);
    }
    public diagAAutoCorredor(java.awt.Frame parent){
        this(parent,true,new CatCorredorAuto());
    }
    private diagAAutoCorredor(java.awt.Frame parent, boolean modal){
        this(parent,modal,new CatCorredorAuto());
    }
    /** Creates new form diagAAutoCorredor */
    private diagAAutoCorredor(java.awt.Frame parent, boolean modal,CatCorredorAuto corredores_usados) {
        super(parent, modal);
        this.corredores_usados = corredores_usados;
        this.corredor_autoV = new CatCorredorAuto();
        //autoinit
        initComponents();
        //customini
        init();
        //frame config
        setTitle(TITLE);
        setLocationRelativeTo(null);
    }
    /**
     * inicializa la tabla con los datos de los competidores cargados
     * el radioButton seleccionado por default
     */
    private void init(){
        rbDNI.setSelected(true);
        try{
            corredor_autoV = new NegCorredorAuto().getTodosMenos(corredores_usados);
            actualiza_tbl(corredor_autoV);
        }catch(SQLException ex){
            lblEstado.setText("Tabla corredor-auto: Error Datos");
            System.err.println("sqlex:"+ex.getMessage());
        }
    }
    private void filtra_corredor_auto(){
        String txt = txtBusqueda.getText();
        if(rbDNI.isSelected()){
            actualiza_tbl(corredor_autoV.filtrarDNI(txt));
        }else if(rbApellido.isSelected()){
            actualiza_tbl(corredor_autoV.filtrarApellido(txt));
        }else{
            throw new IllegalArgumentException("Opcion Desconocida");
        }
    }
    private void autocompleta_patente(){
        String patente = txtPatente.getText();
        if(patente.length()==3){
            patente += "-";
        }
        txtPatente.setText(patente);
    }
    private void actualiza_tbl(final CatCorredorAuto c_aV){
        corredor_autoV_filtrado = (CatCorredorAuto) c_aV.clone();
        final DefaultTableModel tmodel = new NotEditableTableModel();
        if(corredor_autoV_filtrado.isEmpty()){
            tmodel.setColumnIdentifiers(new Object[]{"Sin Datos"});
        }else{
            tmodel.setColumnIdentifiers(new Object[]{"Numero","DNI","Nombre","Apellido","Patente"});
            for(CorredorAuto ca: corredor_autoV_filtrado){
                tmodel.addRow(new Object[]{ca.getNumero_asignado(),ca.getCorredor().getDni(),ca.getCorredor().getNombre(),ca.getCorredor().getApellido(),ca.getAuto().getPatente()});
            }
        }
        tblAutoCorredor.setModel(tmodel);
        
    }
    
    /**
     * en vez de guardar uno nuevo, este deja listo el corredor_auto para que 
     * el que llamo a esta clase lo use.
     */
    private void corredor_auto_seleccionado(){
        int idx = tblAutoCorredor.getSelectedRow();
        if(idx<0)
            return;
        corredor_auto = corredor_autoV_filtrado.get(idx);
        CANCELADO = false;
        dispose();
    }
    /**
     * guarda el nuevo corredor y lo deja listo para que el que llamo a este diag. lo use
     */
    private void aceptar(){
        if(txtDNI.getText().isEmpty() || !DBConnector.es_numero(txtDNI)){
            lblEstado.setText("El DNI Debe ser un numero");
            txtDNI.grabFocus();
            return ;
        }
//        if(!esUnicoDNI()){
//            lblEstado.setText("El DNI Debe ser un unico, ya existe una persona con ese dni");
//            txtBusqueda.setText(txtDNI.getText());
//            txtBusqueda.grabFocus();
//            return ;
//        }
        if(txtNombre.getText().trim().isEmpty()){
            lblEstado.setText("Ingrese un Nombre valido");
            txtNombre.grabFocus();
            return ;
        }
        if(txtApellido.getText().trim().isEmpty()){
            lblEstado.setText("Ingrese un Apellido valido");
            txtApellido.grabFocus();
            return ;
        }
        if(!Utilidades.esPatente(txtPatente.getText())){
            lblEstado.setText("Verifique patente");
            txtPatente.grabFocus();
            return ;
        }
        
        try{
            carreras.entidades.Auto auto = new Auto(txtPatente.getText());
            carreras.entidades.Corredor corredor = new Corredor(txtNombre.getText(), txtApellido.getText(), Integer.parseInt(txtDNI.getText()));
            corredor_auto = new CorredorAuto(auto, corredor);        
            new NegCorredorAuto().addCorredorAuto(corredor_auto);
            CANCELADO = false;
            dispose();
        }catch(SQLException ex){
            lblEstado.setText("Agregar corredor-auto: Error Datos");
            System.err.println("sqlex: "+ex.getMessage());
        }
    }
    //no se usa, asi puede correr con el auto que quieeera!
//    private boolean esUnicoDNI(){
//        try{
//            return new carreras.negocio.Corredor().esUnicoDni(txtDNI.getText());
//        }catch(SQLException ex){
//            System.err.println("sqlex: "+ex.getMessage());
//            return false;
//        }
//    }
    /**
     * cancela toda operacion
     */
    private void cancelar(){
        CANCELADO = true;
        dispose();
    }

    public CorredorAuto getCorredor_auto() {
        return corredor_auto;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jPanel5 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        txtPatente = new javax.swing.JTextField();
        txtBusqueda = new javax.swing.JTextField();
        jPanel4 = new javax.swing.JPanel();
        rbDNI = new javax.swing.JRadioButton();
        rbApellido = new javax.swing.JRadioButton();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        txtDNI = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        txtApellido = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblAutoCorredor = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        lblEstado = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Auto"));
        jPanel5.setLayout(new java.awt.GridLayout(1, 0));

        jLabel4.setText("Patente");
        jPanel5.add(jLabel4);

        txtPatente.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtPatenteKeyReleased(evt);
            }
        });
        jPanel5.add(txtPatente);

        txtBusqueda.setText("Buscar");
        txtBusqueda.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                txtBusquedaFocusGained(evt);
            }
        });
        txtBusqueda.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtBusquedaKeyReleased(evt);
            }
        });

        buttonGroup1.add(rbDNI);
        rbDNI.setText("DNI");
        rbDNI.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbDNIActionPerformed(evt);
            }
        });
        jPanel4.add(rbDNI);

        buttonGroup1.add(rbApellido);
        rbApellido.setText("Apellido");
        rbApellido.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbApellidoActionPerformed(evt);
            }
        });
        jPanel4.add(rbApellido);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos Conductor"));
        jPanel1.setLayout(new java.awt.GridLayout(0, 2));

        jLabel1.setText("DNI");
        jPanel1.add(jLabel1);
        jPanel1.add(txtDNI);

        jLabel2.setText("Nombre");
        jPanel1.add(jLabel2);
        jPanel1.add(txtNombre);

        jLabel3.setText("Apellido");
        jPanel1.add(jLabel3);
        jPanel1.add(txtApellido);

        tblAutoCorredor.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblAutoCorredor.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblAutoCorredorMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblAutoCorredor);

        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton1);

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton2);

        lblEstado.setText("Estado");
        lblEstado.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED));

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(lblEstado, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 560, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(txtBusqueda, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel5, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
                .addContainerGap())
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 520, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(txtBusqueda, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 109, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 168, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel5, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 76, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(lblEstado))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        aceptar();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        cancelar();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void tblAutoCorredorMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblAutoCorredorMouseClicked
        if(evt.getClickCount()==2){
            corredor_auto_seleccionado();
        }
    }//GEN-LAST:event_tblAutoCorredorMouseClicked

    private void txtBusquedaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtBusquedaKeyReleased
        filtra_corredor_auto();
    }//GEN-LAST:event_txtBusquedaKeyReleased

    private void txtBusquedaFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtBusquedaFocusGained
        txtBusqueda.selectAll();
    }//GEN-LAST:event_txtBusquedaFocusGained

    private void rbApellidoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbApellidoActionPerformed
        txtBusqueda.grabFocus();
    }//GEN-LAST:event_rbApellidoActionPerformed

    private void rbDNIActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbDNIActionPerformed
        txtBusqueda.grabFocus();
    }//GEN-LAST:event_rbDNIActionPerformed

    private void txtPatenteKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtPatenteKeyReleased
        if(evt.getKeyCode()==KeyEvent.VK_ENTER){
            aceptar();
        }else{
            autocompleta_patente();
        }
    }//GEN-LAST:event_txtPatenteKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        Configuracion.init_conf(args);
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(diagAAutoCorredor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(diagAAutoCorredor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(diagAAutoCorredor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(diagAAutoCorredor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                diagAAutoCorredor dialog = new diagAAutoCorredor(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
                dialog.dispose();
                System.exit(0);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblEstado;
    private javax.swing.JRadioButton rbApellido;
    private javax.swing.JRadioButton rbDNI;
    private javax.swing.JTable tblAutoCorredor;
    private javax.swing.JTextField txtApellido;
    private javax.swing.JTextField txtBusqueda;
    private javax.swing.JTextField txtDNI;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtPatente;
    // End of variables declaration//GEN-END:variables
}
